package com.util.aliyun;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.util.property.Properties;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by reeves on 2015/12/16.
 */
public class ReplaceImgURL {
    private static final Logger LOGGER = Logger.getLogger(ReplaceImgURL.class);

    //用户头像上传到OSS
    public static String uploadUserPhoto(String imageSrc) throws IOException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");

        try {
            File file = new File(imageSrc);
            InputStream is = new FileInputStream(file);

            // 设置上传文件的一些信息
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentLength(file.length()); // 文件大小的信息是必需的

            //上传文件
            Date date = new Date();
            String upFileName = String.valueOf(date.getTime()) + "." + "jpg";

            String ossFilePath = "kbApp_userPhoto/" + simpleDateFormat.format(date) + upFileName;

            // 创建oss-client
            OSSClient ossClient = new OSSClient(OssConfig.ossConfig.getEndPoint(), OssConfig.ossConfig.getAccessKeyId(), OssConfig.ossConfig.getAccessKeySecret());
            ossClient.putObject(OssConfig.ossConfig.getBucketName(), ossFilePath, is, meta);

            return Properties.Aliyun_Oss_ImagePrefix + ossFilePath;
        } catch (Exception exception) {
            LOGGER.error("上传到阿里云OSS错误" + exception);
            return imageSrc;
        }
    }

}
